package com.jl.jtils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 *
 * @author jiangli  2017/7/30
 * @version v1.0
 */
public class StrUtils {

    private static final int MOBILE_LENGTH = 11;
    private static final int EMAIL_LENGTH = 50;

    /**
     * 空字符串，""
     */
    public static final String EMPTY = "";

    /**
     * 0-9数字字符串
     */
    private static final String NUMERIC = "0123456789";

    /**
     * 英文字符
     */
    private static final char[] LETTERS = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
            'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};


    /**
     * email正则表达式
     */
    private static final Pattern EMAIL_CHECKER = Pattern.compile(
            "^([a-z0-9A-Z]+[-|._]?)+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");

    /**
     * 手机号码正则表达式
     */
    private static final Pattern MOBILE_CHECKER = Pattern.compile("^1\\d{10}$");

    /**
     * 判断字符串是否不为空，非null或者不为空串
     *
     * @param cs 字符串
     * @return null或者空串返回false，反之，返回true
     */
    public static boolean isNotEmpty(CharSequence cs) {
        return !isEmpty(cs);
    }

    /**
     * 判断字符串是否为空，null或者空串
     *
     * @param cs 字符串
     * @return null或者空串返回true，反之，返回false
     */
    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    /**
     * 生成随机长度的字符串
     *
     * @param length 字符串长度
     * @return 随机字符串
     */
    public static String getRandomString(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(LETTERS.length + NUMERIC.length());
            if (number >= LETTERS.length) {
                sb.append(NUMERIC.charAt(number - LETTERS.length));
            } else {
                sb.append(random.nextBoolean() ? LETTERS[number] :
                        String.valueOf(LETTERS[number]).toUpperCase());
            }
        }
        return sb.toString();
    }

    /**
     * 是否为邮箱
     *
     * @param email 待测试的字符串
     * @return 若是，则返回true；否则，返回false
     */
    public static boolean isValidEmail(String email) {
        if (isEmpty(email) || email.length() > EMAIL_LENGTH) {
            return false;
        }
        Matcher matcher = EMAIL_CHECKER.matcher(email);
        return matcher.matches();
    }

    /**
     * 是否为中国的手机号
     *
     * @param mobile 待测试的字符串
     * @return 若是，则返回true；否则，返回false
     */
    public static boolean isValidMobile(String mobile) {
        if (isEmpty(mobile) || mobile.length() != MOBILE_LENGTH) {
            return false;
        }
        Matcher matcher = MOBILE_CHECKER.matcher(mobile);
        return matcher.matches();
    }
}
